<template>
  <div style="padding: 10px 0px; background-color: white; min-height: 100vh">
    <van-form @submit="submitForm">
      <searchable-picker
        v-model="form.applyAscription"
        :columns="dict.type.sys_data_ascription"
        @change="handleChange"
        valueKey="value"
        labelKey="label"
        label="费用归属"
        placeholder="点击选择费用归属"
        :rules="[{ required: true, message: '请选择费用归属' }]"
      />
      <van-field
        v-model="form.applyTime"
        label="申请时间"
        placeholder="申请时间"
        @click="applyTimeFlag = true"
      />
      <van-calendar
        v-model="applyTimeFlag"
        @confirm="onConfirm($event, 'applyTimeFlag', 'applyTime')"
      />
      <searchable-picker
        v-model="form.groupId"
        :columns="dict.type.crm_group"
        v-if="form.applyAscription === '2'"
        valueKey="value"
        labelKey="label"
        label="所属小组"
        placeholder="点击选择所属小组"
        :rules="[{ required: true, message: '请选择所属小组' }]"
      />
      <DeptTreePicker
        ref="treePicker"
        v-if="form.applyAscription === '1'"
        v-model="form.deptId"
        label="所属部门"
        :rules="[{ required: true, message: '请选择归属部门' }]"
      />
      <searchable-picker
        v-model="form.userId"
        :columns="userList"
        v-if="form.applyAscription === '0'"
        valueKey="userId"
        labelKey="userName"
        label="所属人"
        placeholder="请选择所属人"
        :rules="[{ required: true, message: '请选择所属小组' }]"
      />
      <searchable-picker
        v-model="form.customerId"
        :columns="customerList"
        valueKey="customerId"
        labelKey="customerName"
        label="客户名称"
        placeholder="点击选择客户名称"
      />
      <searchable-picker
        v-model="form.orderId"
        :columns="orderList"
        valueKey="orderId"
        labelKey="orderName"
        label="商机名称"
        placeholder="点击选择商机名称"
      />
      <div class="details">
        <div class="details-header">费用明细</div>
        <van-collapse
          v-model="activeNames"
          class="product"
          v-for="(details, index) in form.detailList"
          :key="index"
        >
          <van-collapse-item
            :title="'明细' + (index + 1)"
            :name="index + 1"
            icon="ellipsis"
            class="details-body"
          >
            <div class="details-button">
              <el-button type="text" @click="addExpenses(details, index)"
                >新增</el-button
              >
              <el-button
                type="text"
                style="color: red"
                @click="delExpenses(index)"
                v-if="details.flag !== '1'"
                >删除</el-button
              >
            </div>
            <van-field
              v-model="details.detailsName"
              label="报销项目"
              placeholder="请输入报销项目"
              :rules="[{ required: true, message: '报销项目不能为空' }]"
            />
            <van-field
              v-model="details.detailsSummary"
              label="摘要"
              placeholder="请输入摘要"
              :rules="[{ required: true, message: '请输入摘要' }]"
            />
            <van-field
              v-model="details.detailsAmount"
              label="金额"
              placeholder="请输入金额"
              type="number"
              :rules="[{ required: true, message: '请输入金额' }]"
            />
          </van-collapse-item>
        </van-collapse>
        <div class="details-footer">
          <el-button
            type="text"
            icon="el-icon-circle-plus-outline"
            @click="addExpenses(details)"
            >新增一项</el-button
          >
        </div>
        <div style="height: 10px; background-color: #eceff2"></div>
      </div>
      <van-field
        v-model="form.amount"
        label="合计金额"
        placeholder="请输入合计金额"
        type="number"
        readonly
      />
      <van-field
        v-model="form.loan"
        label="原借款"
        placeholder="请输入原借款"
        type="number"
      />
      <van-field
        v-model="form.refund"
        label="应退款"
        placeholder="请输入应退款"
        type="number"
      />
      <van-field
        v-model="form.opinion"
        rows="3"
        autosize
        label="备注"
        type="textarea"
        placeholder="请输入备注"
        style="margin-bottom: 50px"
      />
      <div class="mobile-footer">
        <van-button
          type="info"
          native-type="submit"
          style="width: 90%; border-radius: 10px"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { getApply, addApply, updateApply } from "@/api/crm/apply";

import { getUserListByStatus } from "@/api/system/user";
import { getCrmOrderAllNoPage } from "@/api/crm/order";
import { getCrmCustomerAllNoPage } from "@/api/crm/customer";

import { getProductListNoPage } from "@/api/crm/product";
export default {
  name: "OrderAdd",
  dicts: ["sys_data_ascription", "crm_group"],
  data() {
    return {
      activeNames: ["1"],
      product: {},
      // 表单参数
      form: {
        applyId: null,
        customerId: null,
        orderId: null,
        applyTime: null,
        amount: null,
        loan: null,
        refund: null,
        remark: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
        applyAscription: "0",
        detailList: [
          { detailsName: "", detailsSummary: "", detailsAmount: null },
        ],
      },
      orderList: [],
      title: "新增",
      applyTimeFlag: false,
      userList: [],
      productList: [],
      customerList: [],
      applyId: "",
    };
  },
  watch: {
    "form.detailList": {
      handler() {
        this.form.amount = this.form.detailList.reduce((total, item) => {
          return total + (Number(item.detailsAmount) || 0);
        }, 0);
      },
      deep: true,
    },
  },
  async created() {
    this.applyId = this.$route.params.applyId;
    await this.getProductListNoPage();
    await this.getUserListByStatus();
    await this.getCrmCustomerAllNoPage();
    await this.getCrmOrderAllNoPage();
    await this.getApply();
  },
  methods: {
    handleChange(val) {
      if (val === "0") {
        this.form.deptId = null;
        this.form.groupId = null;
      } else if (val === "1") {
        this.form.userId = null;
        this.form.groupId = null;
      } else if (val === "2") {
        this.form.deptId = null;
        this.form.groupId = null;
      }
    },
    async getApply() {
      if (this.applyId !== "-1") {
        await getApply(this.applyId).then((res) => {
          if (res.data) {
            this.form = res.data;
          }
          this.getCrmCustomerAllNoPage();
          getCrmOrderAllNoPage({ customerId: this.form.customerId }).then(
            (res) => {
              this.orderList = res.data;
            }
          );
          this.buildActiveNames(this.form.detailList);
        });
      } else {
        this.reset();
      }
    },
    addExpenses(scope, index) {
      if (scope) {
        this.form.detailList.splice(index + 1, 0, {
          detailsName: "",
          detailsSummary: null,
          detailsAmount: null,
        });
      } else {
        this.form.detailList.push({
          detailsName: "",
          detailsSummary: null,
          detailsAmount: null,
        });
      }

      this.buildActiveNames(this.form.detailList);
    },
    delExpenses(index) {
      this.form.detailList.splice(index, 1);
    },
    buildActiveNames(arr) {
      this.activeNames = [];
      for (let i = 1; i <= arr.length; i++) {
        this.activeNames.push(i);
      }
    },

    getCrmOrderAllNoPage() {
      getCrmOrderAllNoPage({ orderType: "0" }).then((res) => {
        this.orderList = res.data;
      });
    },
    getProductListNoPage() {
      getProductListNoPage({}).then((res) => {
        this.productList = res.data;
      });
    },
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    getCrmCustomerAllNoPage() {
      getCrmCustomerAllNoPage({}).then((res) => {
        this.customerList = res.data;
      });
    },
    // 日历回调
    onConfirm(date, flag, fildes) {
      this[flag] = false;
      this.form[fildes] = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
    },
    reset() {
      this.form = {
        applyId: null,
        customerId: null,
        orderId: null,
        applyTime: null,
        amount: null,
        loan: null,
        refund: null,
        remark: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
        applyAscription: "0",
        detailList: [
          { detailsName: "", detailsSummary: "", detailsAmount: null },
        ],
      };
      this.buildActiveNames(this.form.detailList);
    },

    /** 提交按钮 */
    submitForm() {
      if (this.applyId !== "-1") {
        updateApply(this.form).then((response) => {
          this.$toast.success("修改成功");
          this.$router.replace("/crm/apply");
        });
      } else {
        addApply(this.form).then((response) => {
          this.$toast.success("添加成功");
          this.$router.replace("/crm/apply");
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.submitButton {
  width: 95%;
  height: 50px;
  position: fixed;
  top: 90%;
  left: 10px;
}

::v-deep .van-collapse-item__content {
  padding: 0;
}

::v-deep .product .van-collapse-item__title {
  background-color: #eceff2;
  padding: 5px 16px;
}

.details {
  border-bottom: 1px solid #eceff2;

  .details-header {
    padding: 10px 16px 3px;
    color: #323233;
    font-size: 14px;
    line-height: 24px;
    background-color: #fff;
  }

  .details-footer {
    text-align: center;
    .el-button--text {
      font-size: 18px;
    }
  }

  .details-body {
    position: relative;
  }

  .details-button {
    position: absolute;
    z-index: 1;
    right: 10px;
    top: 35px;
  }
}
</style>